<?php
/**
 * This file handles the XML database used by Jabberdrive 
 * to handle it's internal structure.
 * 
 * @author Gustav Knutsson
 */
class jdDatabase{
	
	// Store the single instance of Database
    private static $Instance;

    /**
     * Class contstruct, 
     * can only be called once since using the singleton pattern
     * 
     * @author Gustav Knutsson
     */
    private function __construct(){
    	if(!defined("DATABASE_FILE")){
    		die("<b>jdError:</b> Database file has not been defined");
    	}
    	
    	if(!$this->_hasCreatedDatabase()){
    		$this->_createDatabaseFile();
    	}
    }
    
	/**
	 * Use jdDatabase::getInstance() to get object.
	 * 
	 * @return jdDatabase object
	 * @author Gustav Knutsson
	 */
	public static function getInstance(){
        if (!isset(self::$Instance)) {
            $c = __CLASS__;
            self::$Instance = new $c;
        }

        return self::$Instance;
    }
    
    /**
     * Validates a user against the xml database, if valid the it returns the user ID
     * 
     * @param STRING $username
     * @param STRING $password
     * @return integer
     * 
     * @author Gustav Knutsson
     * @access public
     */
    public function hasUser($username, $password){
    	$xml = $this->_readDatabase();
    	foreach($xml->users as $obj){
    		$user = $obj->user;
    		if($user->username == $username and $user->password == $password and $user->mode == 'enabled'){
    			return $user->id;
    		}
    	}
    	return false;
    }
    
    /**
     * Adds a new file in the database.
     * 
     * @return INTEGER
     * 
     * @author Gustav Knutsson
     * @access public
     */
    public function addFile($filename, $user_id, $date){
    	$xml = $this->_readDatabase();
    	if(!isset($xml->files->file[0])){
    		// We have not created any files yet, save the first file to the database.
    		$sxe = new SimpleXMLElement(file_get_contents(DATABASE_FILE));
			
			/*$file  = $sxe->addChild('files');
			$file->addChild('filename', $filename);
			$file->addChild('fileuserid', $user_id);
			$file->addChild('filestoredate', $date);
			$file->addChild('fileid', "1");// Since this is the first file we are adding*/
			
			$xml_str = $sxe->asXML(DATABASE_FILE);
			
			return 1;
    	}
    }
    
    /**
     * This function checks if the databasefile has been created 
     * and is readable.
     * 
     * @return bool
     * @author Gustav Knutsson
     */
    private function _hasCreatedDatabase(){
    	return file_exists(DATABASE_FILE);	
    }
    
    /**
     * Use this function to create the database and it's initial structure.
     * Should be used in conjunction with the "_hasCreatedDatabase" function
     * 
     * @author Gustav Knutsson
     */
    private function _createDatabaseFile(){
    	$fh = fopen(DATABASE_FILE,"w+");
    	if(!$fh){
    		die("<b>jdError:</b> Could not create file-stream to databasefile: ".DATABASE_FILE);
    	}
    	// Initial structure text.
    	$is  = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    	$is .= "<jdDatabase>\n";
    	$is .= "	<users>\n";
    	
    	// Also create the superadmin user.
    	$is .= "		<user>\n";
    	$is .= "			<id>1</id>\n";
    	$is .= "			<username>".ADMIN_USERNAME."</username>\n";
    	$is .= "			<password>".ADMIN_PASSWORD."</password>\n";
    	$is .= "			<realname>".ADMIN_USERNAME."</realname>\n";
    	$is .= "			<mode>".USE_ADMIN."</mode>\n";
    	$is .= "			<level>4</level>\n";
    	$is .= "		</user>\n";
    	$is .= "	</users>\n";
    	$is .= "	<files>\n";
    	$is .= "	</files>\n";
    	$is .= "</jdDatabase>\n";
    	
    	fwrite($fh, $is, strlen($is)) or die("<b>jdError:</b> Could not write to databasefile stream.");
    	fclose($fh) or die("<b>jsError:</b> Could not close stream to database file");
    }
    
    /**
     * Reads the database into the simpleXMLElement
     * 
     * @return simple_xml_element object
     * 
     * @author Gustav Knutsson
     * @access private
     */
    private function _readDatabase(){
    	$xml = simplexml_load_file(DATABASE_FILE);
    	return $xml;
    }
}
?>